<?php
declare (strict_types = 1);

namespace app\frontend\controller;

use app\BaseController;
use app\frontend\model\User;
use think\facade\Validate;

/**
 * 登录相关功能
 * Class Login
 * @package app\backend\controller
 */
class Login extends BaseController
{
    // 渲染登录页面
    public function login()
    {
        return view();
    }

    // 登录验证
    public function loginCheck()
    {
        // 接收表单数据
        $params['username'] = trim(input('post.username'));
        $params['password'] = trim(input('post.password'));
        // 验证表单数据
        $validate = Validate::rule([
            'username|用户名' => 'require|length:1,20',
            'password|密码' => 'require|length:1,20'
        ]);
        if (!$validate->check($params)) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }
        // 查询数据库中是否有该用户
        $userModel = User::where('username', $params['username'])->find();
        if (empty($userModel)) {
            return json([
                'code' => 2,
                'msg' => '该用户不存在'
            ]);
        }
        // 验证密码是否正确
        $res = password_verify($params['password'], $userModel['password']);
        if (empty($res)) {
            return json([
                'code' => 3,
                'msg' => '密码错误'
            ]);
        }
        // 将用户信息存入session
        session('userInfo', $userModel->toArray());

        return json([
            'code' => 0,
            'msg' => '登录成功'
        ]);
    }

    // 退出登录
    public function logout()
    {
        // 清除session
        session('userInfo', null);

        return json([
            'code' => 0,
            'msg' => '退出成功'
        ]);
    }
}
